package com.orangelife.mobile.surrounding.activity;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.common.sp.CommSp2;
import com.common.util.OrangePhoneUtil;
import com.curry.android.http.HttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.ImageDownloader;
import com.curry.android.util.IntentHelper;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.markupartist.android.widget.PullToRefreshListView;
import com.orangelife.mobile.activities.adapter.ActivityDetailListViewAdapter;
import com.orangelife.mobile.surrounding.adapter.GoodsClassifyListViewAdapter;
import com.orangelife.mobile.surrounding.entity.GoodsEntity;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.shoppingcart.activity.ShoppingCartActivity;
import com.orangelife.mobile.shoppingcart.biz.ShoppingCartBiz;
import com.orangelife.mobile.util.JsonReponseHandler;
import com.orangelife.mobile.util.ToastHelper;
import com.orangelife.mobile.widget.ScrollListView;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 商户详情有列表的类
 * Created by yyx
 * on 2015/10/16.
 */
public class CommercialListActivity extends OrangeLifeBaseActivity {

    @Bind(R.id.ib_title_left)
    LinearLayout ibTitleLeft;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.iv_title_call)
    ImageView ivTitleCall;
    @Bind(R.id.iv_title_shopping_cart)
    ImageView ivTitleShoppingCart;
    @Bind(R.id.tvGoodNumber)
    TextView tvGoodNumber;
    @Bind(R.id.flShoppingCart)
    FrameLayout flShoppingCart;
    @Bind(R.id.ll_score)
    LinearLayout llScore;
    @Bind(R.id.rl_title)
    RelativeLayout rlTitle;
    @Bind(R.id.lvGoods)
    PullToRefreshListView lvGoods;

    ImageView ivCommercial;
    TextView tvCommercial;
    ScrollListView slList;
    LinearLayout llHistoryRecord;
    TextView tvFirst;
    TextView tvSecond;

    /**
     * 商户详情数据
     */
    private Map<String, Object> mapDetail = null;

    private View headerView;
    private ImageDownloader image = ImageDownloader.getImageDownloader();
    /**
     * 一页中数据的条数，初始设置为7条
     */
    private int pageSize = Constant.PAGE_SIZE_DEFAULLT;
    /**
     * 初始页，初始化为第一页
     */
    private int pageNo = Constant.PAGE_NO_DEFAULT;
    /**
     * adapter
     */
    private GoodsClassifyListViewAdapter<Map<String, Object>> adapter;
    /**
     * 分辨是刷新还是加载更多
     */
    private int flags = 1;
    private Handler mHandler;
    private List<Map<String, Object>> list;
    private List<Map<String, Object>> list2;
    private Intent intent;
    private String merID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_circumtesco_commerciallist);
        ButterKnife.bind(this);
        findView();
    }

    protected void onResume() {
        super.onResume();
        if (getGoodsNumber() == 0) {
            tvGoodNumber.setVisibility(View.GONE);
        } else {
            tvGoodNumber.setVisibility(View.VISIBLE);
            tvGoodNumber.setText(getGoodsNumber() + "");
        }
    }

    /**
     * 赋值
     */
    private void findView() {

        intent = getIntent();
        merID = intent.getStringExtra("merID");
        if(merID == null){
            merID = GoodsEntity.getMerID();
        }
        mHandler = new Handler();
        setHeaderView();
        setAdapter();
        pullListView();
        tvFirst.setText("商品列表");
        tvSecond.setText("商户详情");
        llHistoryRecord.setOnClickListener(listener);
        flShoppingCart.setOnClickListener(listener);
        ivTitleCall.setOnClickListener(listener);
        if (!GoodsEntity.isClick()) {
            getDataFromServer();
            getDetail();

        } else {
            GoodsEntity.setIsClick(false);
            mapDetail = GoodsEntity.getMap();
            setDetail();

        }
        pageNo = 1;
        getDiscountList(pageSize, pageNo);
        ToastHelper.getInstance().init(this);

    }

    @Override
    protected void onNewIntent(Intent intent) {
        merID = intent.getStringExtra("merID");
        getDataFromServer();
        getDetail();
        pageNo = 1;
        getDiscountList(pageSize,pageNo);
    }

    /**
     * 获取购物车数量
     * @return
     */
    private int getGoodsNumber(){
        return ShoppingCartBiz.getGoodsCount();
    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.ll_history_record:
                    finish();
                    GoodsEntity.setMerID(merID);
                    IntentHelper.getInstances().getIntent(CommercialListActivity.this, CommercialDetailActivity.class);
                    break;
                case R.id.iv_title_call:
                    //打电话
                    OrangePhoneUtil.callCustomerService2(CommercialListActivity.this);
                    break;
                case R.id.flShoppingCart:
                    //跳转购物车页面
                    IntentHelper.getInstances().getIntent(CommercialListActivity.this, ShoppingCartActivity.class);
                    finish();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 设置下拉刷新的头部
     */
    private void setHeaderView() {
        headerView = getLayoutInflater().inflate(R.layout.item_circumtesco_pl_header, null);
        ivCommercial = (ImageView) headerView.findViewById(R.id.ivCommercial);
        tvCommercial = (TextView) headerView.findViewById(R.id.tvCommercial);
        slList = (ScrollListView) headerView.findViewById(R.id.slList);
        llHistoryRecord = (LinearLayout) headerView.findViewById(R.id.ll_history_record);
        tvFirst = (TextView) headerView.findViewById(R.id.tvFirst);
        tvSecond = (TextView) headerView.findViewById(R.id.tvSecond);
        lvGoods.addHeaderView(headerView);
    }

    /**
     * 下拉刷新的进度条
     */
    private void getDataFromServer() {
        dialog = DialogHelper.getInstance().createLoadingDialog(this,
                Constant.LOADING);
        dialog.show();
    }

    /**
     * 设置优惠列表的adapter
     */
    private void setAdapter() {
        /* 设置listview的adapter */
        list = new ArrayList<Map<String, Object>>();
        list2 = new ArrayList<Map<String, Object>>();
        adapter = new GoodsClassifyListViewAdapter<Map<String, Object>>(
                this, list, false);
        lvGoods.setPullLoadEnable(false);
        lvGoods.setAdapter(adapter);
    }

    /**
     * 获取商户详情数据
     */
    private void getDetail() {
        Map<String, Object> mapSubmit = new HashMap<String, Object>();
        mapSubmit.put("commID", CommSp2.getCommID());
        mapSubmit.put("{merID}", merID);
        //        mapSubmit.put("{merID}", "39babda8-f27e-4163-9b77-5a40c4932d34");
        Map<String, Object> rootMap = new HashMap<String, Object>();
        rootMap.put("map", mapSubmit);
        rootMap.put("url", Constant.URL_CIRCUMTESO_COMMERCIAL_DETAIL);
        rootMap.put("wat", 6);
        new JSONRequest(JSONRequest.GET, rootMap, handler, HttpUtil.ACTION_URI);
    }

    /**
     * 获取列表数据
     *
     * @param pageSize 每页的条数
     * @param pageNo   初始页
     */
    private void getDiscountList(int pageSize, int pageNo) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("comID", CommSp2.getCommID());
        map.put("merID", merID);
        //        map.put("comID", "00c2aee8-4a02-4455-8335-4caf2b8f5295");
        //        map.put("merID", "5e583401-d87e-46cd-b729-85ecf9b6b61b");
        map.put("pageIndex", pageNo);
        map.put("pageSize", pageSize);
        Map<String, Object> rootMap = new HashMap<String, Object>();
        rootMap.put("map", map);
        rootMap.put("url", Constant.URL_CIRCUMTESO_COMMERCIAL_LIST);
        rootMap.put("wat", 2);
        new JSONRequest(JSONRequest.GET, rootMap, handler, HttpUtil.ACTION_URI);
    }

    /**
     * 处理返回的信息数据
     */
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 6:
                    DialogHelper.closeDialog(dialog);
                    mapDetail = new HashMap<String, Object>();
                    mapDetail = (Map<String, Object>) JSONHelper.jsonToMap(
                            msg.obj.toString()).get("entity");
                    setDetail();
                    break;
                case 2:
                    list2 = JsonReponseHandler.getListFromJson(
                            String.valueOf(msg.obj), adapter, dialog);

                    updateListView(list2);
                    break;

                case 500:
                    DialogHelper.closeDialog(dialog);
                    ToastHelper.getInstance()._toast(msg.obj.toString());
                    break;
                case 1011:
                    isLogin(dialog);
                    break;
                default:
                    break;
            }
        }

    };

    /**
     * 设置详情
     */
    private void setDetail() {
        if(mapDetail != null && mapDetail.size() != 0) {
            GoodsEntity.setMap(mapDetail);
            tvTitle.setText(mapDetail.get("merchantName").toString());
            tvCommercial.setText(mapDetail.get("merchantName").toString());
            String url = mapDetail.get("merchantLogo").toString();
            image.download(url, ivCommercial, ImageDownloader.ImageSize.IMAGE_SIZE_EXTRA_SMALL_SQUARE_JPG);
            List<Map<String, Object>> listSummary = (List<Map<String, Object>>) mapDetail.get("summary");
            ActivityDetailListViewAdapter adapter = new ActivityDetailListViewAdapter(
                    this, listSummary);
            slList.setAdapter(adapter);
        }

    }

    /**
     * 下拉刷新列表
     */
    private void pullListView() {
        lvGoods.setXListViewListener(new PullToRefreshListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        // list.clear();
                        flags = 1;
                        pageNo = 1;
                        getDiscountList(pageSize, pageNo);
                        onLoad();
                        adapter.setList(list);
                        adapter.notifyDataSetChanged();
                    }
                }, 2000);
            }

            @Override
            public void onLoadMore() {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        flags = 0;
                        pageNo += 1;
                        getDiscountList(pageSize, pageNo);
                        onLoad();
                        if (list != null) {
                            adapter.setList(list);
                            adapter.notifyDataSetChanged();
                        }
                    }
                }, 2000);
            }
        });
    }

    /**
     * 刷新 拉下列表
     *
     * @param list2
     */
    private void updateListView(List<Map<String, Object>> list2) {
        if (list2 == null) {
            lvGoods.setPullLoadEnable(false);
            if (flags == 1) {
                lvGoods.setPullLoadEnable(true);
                list.clear();
                adapter.setList(list);
                adapter.notifyDataSetChanged();
            }
        }
        if (list2 != null && list != null) {
            if (list2.size() == 0) {
                lvGoods.setPullLoadEnable(false);
                if(flags == 1){
                    list.clear();
                }
                list.addAll(list2);
                adapter.setList(list);
                adapter.notifyDataSetChanged();
            } else {
                if (flags == 1) {
                    list.clear();
                }
                    lvGoods.setPullLoadEnable(true);
                    list.addAll(list2);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
            }
        } else {
            lvGoods.setPullLoadEnable(false);
        }
    }

    @SuppressWarnings("deprecation")
    private void onLoad() {
        lvGoods.stopRefresh();
        lvGoods.stopLoadMore();
        lvGoods.setRefreshTime(new Date().toLocaleString());
    }
}
